local skynet = require "skynet"
local mysql = require "mysql"
local snax = require "snax"
local cluster = require "cluster"
local CMD = require "center_proto"
local buffrw = require "buffrw"
local db = require "dblib"

local MSGSER = {}
local myDB = {}

function myDB.AddParaIn(querymsg, arg)
    arg = arg or ""
    querymsg = querymsg..string.format("\""..arg.."\",")
	return querymsg
end

function myDB.AddParaOut(querymsg, arg)
	querymsg = querymsg..arg
	return querymsg
end

--************************消息服务负责邮件消息*************************************

-----------------------------------------------------
--消息类型(MsgType)|       备注
-----------------------------------------------------
-- 200             |普通消息，带有物品;
-----------------------------------------------------
-- 201             |比赛消息，奖励钻石，金币;弃赛提示
-----------------------------------------------------
-- 202             |比赛消息，奖励话费;
-----------------------------------------------------
-- 300             |游戏断线结算消息;
-----------------------------------------------------
-- 301             |领取202消息中奖励的通知;
-----------------------------------------------------

function MSGSER.SplitAward(msg)
    
    local num = 0
    local temp_msg={}
    if msg == nil then 
		return temp_msg, num
	end
	
	local pos = 0
	local old 
	local substr
	while true do 
		old = pos+1
		pos=string.find(msg,",",pos+1)
		if pos then 
			substr = string.sub(msg,old,pos-1)
		else
			substr = string.sub(msg,old)
		end
		
		local temp = string.find(substr,"|",1)
		local k= string.sub(substr,1,temp-1)
		local v= string.sub(substr,temp+1)
		temp_msg[tonumber(k)]=tonumber(v)
        num = num + 1
		if pos==nil  then 
			break
		end
	end
	return temp_msg, num
end

--用户是否有新消息，消息系统 
function  MSGSER.HasNewMsg(playid, msg)

    local BuffRead = buffrw.BuffRead.new(msg)
    local msgid = BuffRead:int8()
    local sqlstr = "call pr_IsHasNewMsg("..playid..","..msgid..",@ReturnVal_);"
    local res_sql = "select @ReturnVal_;"
    local res1,res2 = db.call(sqlstr,res_sql)

    local res1,res2 = db.call("call  pr_IsHasNewMsg("..tonumber(playid)..","..tonumber(msgid)..",@ReturnVal_);","select @ReturnVal_;")

    local result = res2[1]['@ReturnVal_']
    skynet.error("[msgser] HasNewMsg result ",msgid,playid,result)
    local BuffWrite = buffrw.BuffWrite.new()
    BuffWrite:int4(result)
    local re = {mcmd = CMD.Main_MsgSer_module,scmd = CMD.Sub_MsgSerToModule_HasNewMsgResult, msg = BuffWrite.buff } 
    return re  
end

--返回新消息标题
function MSGSER.GetNewMsg(playid, msg)
  
    local BuffRead = buffrw.BuffRead.new(msg)
    local msgid = BuffRead:int8() 
    skynet.error("[msgser] HasNewMsg msg len ",playid,msgid)

    local res1 = db.call("call  pr_GetNewMsg("..tonumber(playid)..","..tonumber(msgid)..")")
    skynet.error("[msgser] HasNewMsg msg len ",#res1[1])

    if #res1[1] == 0 then  -- 返回列表长度        
        return 
    end
    local maglen=#res1[1]
    local BuffWrite = buffrw.BuffWrite.new()  

    BuffWrite:int2(maglen) --消息个数 word
    for index,msg_obj in pairs(res1[1]) do
        BuffWrite:int8(msg_obj['nMsgId'])--消息id int
        BuffWrite:int4(msg_obj['nMsgType'])--消息类型 int 
        BuffWrite:int1(msg_obj['nIsRead'])-- 是否已读 bool
        BuffWrite:str(msg_obj['sMsgTitle'],128) -- 消息标题 string len 128            
        BuffWrite:int8(msg_obj['tm'])--时间 long
        BuffWrite:int4(msg_obj['nIsReward'])--是否已领奖 0：没有奖励 1：有奖励 2：已领奖 
        local award, awardnum= MSGSER.SplitAward(msg_obj['nAwardType']) --拆封奖励的字符串
        skynet.error("[msgser] HasNewMsg ",msg_obj['nAwardType'],awardnum)
        BuffWrite:int4(awardnum)-- 奖励个数
        for k, v in pairs(award) do  
            skynet.error(k,v)
            BuffWrite:int4(k)
            BuffWrite:int4(v)
        end       
    end
    local re = {mcmd = CMD.Main_MsgSer_module,scmd = CMD.Sub_MsgSerToModule_NewMsgBack, msg = BuffWrite.buff } 
    return re  
end

--返回消息内容以及钻石金币更新
function MSGSER.GetNewMsgBody(playid, msg)
    local BuffRead = buffrw.BuffRead.new(msg)
    local msgid = BuffRead:int8() 
    skynet.error("[msgser] GetNewMsgBody msgid ",msgid)
    local BuffWrite = buffrw.BuffWrite.new()
    local queryin = "call  pr_GetMsgBody("
    queryin = myDB.AddParaIn(queryin, tonumber(playid))
    queryin = myDB.AddParaIn(queryin, tonumber(msgid))
    
    local queryout = ""
    queryout = myDB.AddParaOut(queryout, "@MsgType,")
    queryout = myDB.AddParaOut(queryout, "@MsgTitle,")
    queryout = myDB.AddParaOut(queryout, "@MsgBody,")
    queryout = myDB.AddParaOut(queryout, "@IsReward") 
  
    local res1,res2 = db.call(queryin..queryout..");", "select "..queryout)
    local nMsgType=res2[1]['@MsgType']
    BuffWrite:int8(msgid)
    if nMsgType == nil then 
        skynet.error("[msgser] GetNewMsgBody msgid is nil ",msgid)
        nMsgType = 0
        BuffWrite:int4(nMsgType)
        local result = {mcmd = CMD.Main_MsgSer_module,scmd = CMD.Sub_MsgSerToModule_MsgInfoBack, msg = BuffWrite.buff } 
        return result   
    end  
    
    BuffWrite:int4(nMsgType)    
    BuffWrite:str(res2[1]['@MsgTitle'],128)
    BuffWrite:str(res2[1]['@MsgBody'],1024)
    BuffWrite:int4(res2[1]['@IsReward'])--是否已领奖 0：没有奖励 1：有奖励 2：已领奖 
    BuffWrite:int2(#res1[1])
    skynet.error("[msgser] GetNewMsgBody msgid ",msgid,res2[1]['@MsgType'],res2[1]['@MsgBody'],#res1[1])
 
    if #res1[1] > 0 then
        for index,table_obj in pairs(res1[1]) do
            BuffWrite:int4(table_obj['nAwardType'])
            BuffWrite:int4(table_obj['nAwardNum'])
            skynet.error("awardtype ",table_obj['nAwardType']," awardnum ",table_obj['nAwardNum'])
        end
    end
    local result = {mcmd = CMD.Main_MsgSer_module,scmd = CMD.Sub_MsgSerToModule_MsgInfoBack, msg = BuffWrite.buff } 
    return result   
end

--删除消息
function  MSGSER.DeleteMsg(playid, msg)--删除消息

    local BuffRead = buffrw.BuffRead.new(msg)
    local msgidnum = BuffRead:int4() 
    
    local BuffWrite = buffrw.BuffWrite.new()
    BuffWrite:int4(1)
    BuffWrite:int4(msgidnum)
    for i=1 ,msgidnum do    
        local msgid=BuffRead:int8()        
        local r1, r2 = db.call("call  pr_DeleteMsg("..tonumber(msgid)..",@ReturnVal)", "select @ReturnVal")

        local result = r2[1]['@ReturnVal']
        skynet.error("[msgser] DeleteMsg msgid ",msgid,result)
        if result ~=1 then 
            break
        end
        BuffWrite:int8(msgid)
    end
    local re = {mcmd = CMD.Main_MsgSer_module,scmd = CMD.Sub_MsgSerToModule_MsgDeleteBack, msg = BuffWrite.buff } 
    return re  
    
end

function MSGSER.GetMsgAward(playid, msg)

    local TimeNow  = os.date("%Y-%m-%d %H:%M:%S", os.time())
    local BuffRead = buffrw.BuffRead.new(msg)  
    local BuffWrite = buffrw.BuffWrite.new()   
    local msgid = BuffRead:int8()
    local phone = BuffRead:int8()
    local flag = BuffRead:int4() --客户端区分领奖场景 1:消息系统领奖  0:比赛完领奖
    skynet.error("[msgser] pr_GetAwardMsg ",playid,msgid,phone)
    local sql1 = "call  pr_GetAwardMsg("..playid..","..msgid..","..phone..",@ReturnVal,@MsgTitle,@MsgType)"
    local sql2 = "select @ReturnVal,@MsgTitle,@MsgType"
    local r1, r2 = db.call(sql1, sql2)

    local result = r2[1]['@ReturnVal']
    local msgtype = r2[1]['@MsgType']
    skynet.error("[msgser] GetMatchMsgAward result ",result)   
    BuffWrite:int4(flag)
    BuffWrite:int4(result)
    BuffWrite:int8(phone)
    BuffWrite:int8(msgid)
    if result == 1 then
        local title = r2[1]['@MsgTitle'] 
        local AwardLen = #r1[1]
        BuffWrite:int4(AwardLen)
        for index,Award_obj in pairs(r1[1]) do
            local AwardType = Award_obj['nAwardType']
            local AwardNum = Award_obj['nAwardNum']
            if msgtype == 202 then 
                title = title.."已领取"
                local goods = nil
                if AwardType == 1 then 
                    goods = "钻石。"
                elseif AwardType == 2 then 
                    goods = "老友豆。"
                elseif AwardType == 3 then 
                    goods = "元话费，"
                end
               
                local body = "你在"..TimeNow.."领取"..AwardNum..goods
                if phone >0 then 
                    body = body.."充值号码为:"..tostring(phone).."，我们将在三个工作日内把奖励发放到你的手机，请注意短信提示。"
                end

                local res1, res2 = db.call("call  pr_Addmsg("..playid..",301,\""..title.."\",\""..body.."\",@ReturnVal,@MsgId)", "select @ReturnVal,@MsgId")
              
                if res2[1]['@MsgTitle'] ~= 1 then 
                    skynet.error("[msgser] GetMatchMsgAward pr_Addmsg fail")
                end
            end
            BuffWrite:int4(AwardType)--是否有奖励
            BuffWrite:int4(AwardNum)--是否有奖励
        end
    end
    
    local re = {mcmd = CMD.Main_MsgSer_module,scmd = CMD.Sub_ModuleToMsgSer_GetMailAwardResult, msg = BuffWrite.buff } 
    return re  

end

function response.request_msg(conf)--{cmd,playid,msg}

    skynet.error("[msgser] request_msg",conf.playid,conf.cmd)
    if conf.cmd == CMD.Sub_ModuleToMsgSer_HasNewMsgReq then --获取是否有消息
        re = MSGSER.HasNewMsg(conf.playid, conf.msg)
        return re
    elseif conf.cmd == CMD.Sub_ModuleToMsgSer_GetNewMsgReq then --获取新消息
        re = MSGSER.GetNewMsg(conf.playid, conf.msg)
        return re
    elseif conf.cmd == CMD.Sub_ModuleToMsgSer_GetMsgInfoReq then --获取消息详情
        re = MSGSER.GetNewMsgBody(conf.playid, conf.msg)
        return re
    elseif conf.cmd == CMD.Sub_ModuleToMsgSer_DeleteMsgReq then --删除消息
        re = MSGSER.DeleteMsg(conf.playid, conf.msg)
        return re
    elseif conf.cmd == CMD.Sub_ModuleToMsgSer_GetMailAward then --领取奖励
        re = MSGSER.GetMsgAward(conf.playid, conf.msg)
        return re
    end 
    
end

function init( ... )
	skynet.error("msgser server start:")
	snax.enablecluster()
end

function exit(...)
	skynet.error ("msgser server exit:", ...)
end